import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { Button, message, Modal, Form, Input, Popconfirm, Tag, Space, Tooltip, Select, Avatar, Badge, Tabs, Empty, Drawer, Transfer, List, Card, Typography, Row, Col } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, InfoCircleOutlined, ApartmentOutlined, AppstoreOutlined, TeamOutlined, SettingOutlined, UserSwitchOutlined, LinkOutlined } from '@ant-design/icons';
import { getDeviceGroupList, createDeviceGroup, updateDeviceGroup, deleteDeviceGroup, addDevicesToGroup, removeDevicesFromGroup, getDevicesByGroup, getGroupsByDevice } from '@/services/deviceGroup';
import { getDeviceList } from '@/services/device';
import { history } from 'umi';

const { TabPane } = Tabs;
const { Title, Text, Paragraph } = Typography;

const iconOptions = [
  { value: 'apartment', label: '门禁管理', icon: <ApartmentOutlined /> },
  { value: 'setting', label: '设备配置', icon: <SettingOutlined /> },
  { value: 'appstore', label: '智能控制', icon: <AppstoreOutlined /> },
  { value: 'team', label: '人员管理', icon: <TeamOutlined /> },
  { value: 'userswitch', label: '权限分配', icon: <UserSwitchOutlined /> },
];

const DeviceGroup = () => {
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [updateModalVisible, setUpdateModalVisible] = useState(false);
  const [deviceManageVisible, setDeviceManageVisible] = useState(false);
  const [currentGroup, setCurrentGroup] = useState({});
  const [groupDevices, setGroupDevices] = useState([]);
  const [allDevices, setAllDevices] = useState([]);
  const [selectedDeviceKeys, setSelectedDeviceKeys] = useState([]);
  const [deviceLoading, setDeviceLoading] = useState(false);
  const [deviceDetailVisible, setDeviceDetailVisible] = useState(false);
  const [currentDevice, setCurrentDevice] = useState({});
  const [targetKeys, setTargetKeys] = useState([]);
  const [transferLoading, setTransferLoading] = useState(false);
  
  const actionRef = useRef();
  const [form] = Form.useForm();
  const [updateForm] = Form.useForm();

  // 获取分组下的设备
  const fetchGroupDevices = async (groupId) => {
    setDeviceLoading(true);
    try {
      const res = await getDevicesByGroup({ group_id: groupId });
      if (res.success) {
        setGroupDevices(res.data.data || []);
      } else {
        message.error('获取分组设备失败');
      }
    } catch (error) {
      message.error('获取分组设备失败：' + error.message);
    } finally {
      setDeviceLoading(false);
    }
  };

  // 获取所有设备用于分配
  const fetchAllDevices = async () => {
    setTransferLoading(true);
    try {
      const res = await getDeviceList({ pageSize: 1000 });
      if (res.success) {
        const devices = res.data?.data || [];
        setAllDevices(devices);
        
        // 设置已在分组的设备为目标值
        const groupDeviceIds = groupDevices.map(item => item.id.toString());
        setTargetKeys(groupDeviceIds);
      } else {
        message.error('获取设备列表失败');
      }
    } catch (error) {
      message.error('获取设备列表失败：' + error.message);
    } finally {
      setTransferLoading(false);
    }
  };

  // 打开设备管理抽屉
  const openDeviceManagement = async (group) => {
    setCurrentGroup(group);
    setDeviceManageVisible(true);
    await fetchGroupDevices(group.id);
  };

  // 创建设备分组
  const handleCreate = async (values) => {
    try {
      await createDeviceGroup(values);
      message.success('创建成功');
      setCreateModalVisible(false);
      form.resetFields();
      if (actionRef.current) {
        actionRef.current.reload();
      }
    } catch (error) {
      message.error('创建失败：' + error.message);
    }
  };

  // 更新设备分组
  const handleUpdate = async (values) => {
    try {
      await updateDeviceGroup({
        ...values,
        id: currentGroup.id,
      });
      message.success('更新成功');
      setUpdateModalVisible(false);
      if (actionRef.current) {
        actionRef.current.reload();
      }
    } catch (error) {
      message.error('更新失败：' + error.message);
    }
  };

  // 删除设备分组
  const handleDelete = async (id) => {
    try {
      await deleteDeviceGroup(id);
      message.success('删除成功');
      if (actionRef.current) {
        actionRef.current.reload();
      }
    } catch (error) {
      message.error('删除失败：' + error.message);
    }
  };

  // 打开编辑模态框
  const showEditModal = (record) => {
    setCurrentGroup(record);
    setUpdateModalVisible(true);
    updateForm.setFieldsValue({
      name: record.name,
      description: record.description,
      icon: record.icon || 'apartment',
    });
  };

  // 设备分配变更
  const handleTransferChange = (newTargetKeys) => {
    setTargetKeys(newTargetKeys);
  };

  // 保存设备分配
  const saveDeviceAssignment = async () => {
    try {
      // 计算需要添加和删除的设备
      const originalDeviceIds = groupDevices.map(d => d.id.toString());
      const newDeviceIds = targetKeys;
      
      // 需要添加的设备
      const devicesToAdd = newDeviceIds.filter(id => !originalDeviceIds.includes(id));
      
      // 需要删除的设备
      const devicesToRemove = originalDeviceIds.filter(id => !newDeviceIds.includes(id));
      
      // 执行添加操作
      if (devicesToAdd.length > 0) {
        await addDevicesToGroup(currentGroup.id, devicesToAdd.map(id => parseInt(id)));
      }
      
      // 执行删除操作
      if (devicesToRemove.length > 0) {
        await removeDevicesFromGroup(currentGroup.id, devicesToRemove.map(id => parseInt(id)));
      }
      
      message.success('设备分配已更新');
      
      // 刷新分组设备列表
      await fetchGroupDevices(currentGroup.id);
      
      // 重新加载分组列表，更新设备数量
      if (actionRef.current) {
        actionRef.current.reload();
      }
      
    } catch (error) {
      message.error('更新设备分配失败：' + error.message);
    }
  };

  // 设备详情
  const showDeviceDetail = (device) => {
    setCurrentDevice(device);
    setDeviceDetailVisible(true);
  };

  // 渲染分组图标
  const renderGroupIcon = (icon) => {
    const matchedIcon = iconOptions.find(option => option.value === icon);
    if (matchedIcon) {
      return matchedIcon.icon;
    }
    return <ApartmentOutlined />;
  };

  // 新增跳转到设备列表并过滤分组设备的功能
  const viewDevicesInList = (groupId) => {
    history.push(`/device/list?group_id=${groupId}`);
  };

  // 在renderDeviceCard函数中添加跳转功能
  const renderDeviceCard = (device) => (
    <Card 
      size="small" 
      title={device.device_name}
      style={{ marginBottom: 16 }}
      extra={
        <Button 
          type="link" 
          size="small" 
          icon={<InfoCircleOutlined />} 
          onClick={() => showDeviceDetail(device)}
        >
          详情
        </Button>
      }
    >
      <div style={{ marginBottom: 8 }}>
        <Tag>{device.device_no}</Tag>
        <Tag color={device.status === 1 ? 'green' : device.status === 0 ? 'default' : 'red'}>
          {device.status === 1 ? '正常' : device.status === 0 ? '离线' : '故障'}
        </Tag>
      </div>
      <div>
        <Button 
          type="link" 
          size="small" 
          style={{ padding: 0 }}
          onClick={(e) => {
            e.stopPropagation();
            history.push(`/device/list?id=${device.id}`);
          }}
        >
          在设备列表中查看
        </Button>
      </div>
    </Card>
  );

  // 修改columns定义，完善交互
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      hideInSearch: true,
      width: 80,
    },
    {
      title: '分组名称',
      dataIndex: 'name',
      width: 180,
      render: (text, record) => (
        <Space>
          <Avatar 
            icon={renderGroupIcon(record.icon || 'apartment')} 
            style={{ backgroundColor: '#1890ff' }}
            size="small"
          />
          <span>{text}</span>
        </Space>
      ),
    },
    {
      title: '描述',
      dataIndex: 'description',
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '设备数量',
      dataIndex: 'device_count',
      hideInSearch: true,
      width: 100,
      render: (text, record) => (
        <a onClick={() => openDeviceManagement(record)}>
          <Badge count={text || 0} showZero style={{ backgroundColor: text ? '#1890ff' : '#d9d9d9' }} />
        </a>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      hideInSearch: true,
      width: 180,
      valueType: 'dateTime',
    },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      fixed: 'right',
      render: (_, record) => [
        <Tooltip title="编辑分组" key="edit">
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            onClick={() => showEditModal(record)}
          />
        </Tooltip>,
        <Tooltip title="管理设备" key="devices">
          <Button 
            type="link" 
            icon={<InfoCircleOutlined />} 
            onClick={() => openDeviceManagement(record)}
          />
        </Tooltip>,
        <Tooltip title="查看分组设备列表" key="viewInList">
          <Button 
            type="link" 
            icon={<LinkOutlined />} 
            onClick={() => viewDevicesInList(record.id)}
          />
        </Tooltip>,
        <Popconfirm
          key="delete"
          title="确定要删除此分组吗？"
          onConfirm={() => handleDelete(record.id)}
          okText="确定"
          cancelText="取消"
        >
          <Tooltip title="删除分组">
            <Button type="link" danger icon={<DeleteOutlined />} />
          </Tooltip>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable
        headerTitle="设备分组列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="create"
            onClick={() => {
              form.resetFields();
              form.setFieldsValue({ icon: 'apartment' });
              setCreateModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建分组
          </Button>,
        ]}
        request={async (params) => {
          const { current, pageSize, ...rest } = params;
          const query = {
            page: current,
            pageSize,
            ...rest,
          };
          try {
            const response = await getDeviceGroupList(query);
            return {
              data: response.data?.data || [],
              success: response.success,
              total: response.data?.total || 0,
            };
          } catch (error) {
            message.error('获取设备分组列表失败');
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        columns={columns}
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
        }}
        scroll={{ x: 1000 }}
      />

      {/* 创建分组模态框 */}
      <Modal
        title="创建设备分组"
        visible={createModalVisible}
        onCancel={() => setCreateModalVisible(false)}
        footer={null}
        width={520}
      >
        <Form form={form} onFinish={handleCreate} layout="vertical" initialValues={{ icon: 'apartment' }}>
          <Form.Item
            name="name"
            label="分组名称"
            rules={[{ required: true, message: '请输入分组名称' }]}
          >
            <Input placeholder="请输入分组名称" />
          </Form.Item>
          
          <Form.Item name="icon" label="分组图标">
            <Select placeholder="请选择图标">
              {iconOptions.map(option => (
                <Select.Option key={option.value} value={option.value}>
                  <Space>
                    {option.icon}
                    <span>{option.label}</span>
                  </Space>
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          
          <Form.Item name="description" label="描述">
            <Input.TextArea placeholder="请输入分组描述" rows={4} />
          </Form.Item>
          
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
              <Button onClick={() => setCreateModalVisible(false)}>取消</Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 编辑分组模态框 */}
      <Modal
        title="编辑设备分组"
        visible={updateModalVisible}
        onCancel={() => setUpdateModalVisible(false)}
        footer={null}
        width={520}
      >
        <Form form={updateForm} onFinish={handleUpdate} layout="vertical">
          <Form.Item
            name="name"
            label="分组名称"
            rules={[{ required: true, message: '请输入分组名称' }]}
          >
            <Input placeholder="请输入分组名称" />
          </Form.Item>
          
          <Form.Item name="icon" label="分组图标">
            <Select placeholder="请选择图标">
              {iconOptions.map(option => (
                <Select.Option key={option.value} value={option.value}>
                  <Space>
                    {option.icon}
                    <span>{option.label}</span>
                  </Space>
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          
          <Form.Item name="description" label="描述">
            <Input.TextArea placeholder="请输入分组描述" rows={4} />
          </Form.Item>
          
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
              <Button onClick={() => setUpdateModalVisible(false)}>取消</Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 设备管理抽屉 - 增加导航到设备列表功能 */}
      <Drawer
        title={
          <Space>
            <Avatar 
              icon={renderGroupIcon(currentGroup.icon || 'apartment')} 
              style={{ backgroundColor: '#1890ff' }}
            />
            <span>{currentGroup.name} - 设备管理</span>
          </Space>
        }
        width={820}
        placement="right"
        onClose={() => setDeviceManageVisible(false)}
        visible={deviceManageVisible}
        extra={
          <Space>
            <Button 
              onClick={() => viewDevicesInList(currentGroup.id)}
              type="primary"
            >
              在设备列表中查看
            </Button>
            <Button onClick={() => setDeviceManageVisible(false)}>关闭</Button>
          </Space>
        }
      >
        <Tabs
          defaultActiveKey="1"
          items={[
            {
              key: '1',
              label: '分组设备',
              children: groupDevices.length > 0 ? (
                <List
                  dataSource={groupDevices}
                  loading={deviceLoading}
                  rowKey="id"
                  grid={{ gutter: 16, column: 2 }}
                  renderItem={item => (
                    <List.Item>
                      {renderDeviceCard(item)}
                    </List.Item>
                  )}
                />
              ) : (
                <Empty description="暂无设备" />
              ),
            },
            {
              key: '2',
              label: '设备分配',
              children: (
                <>
                  <div style={{ marginBottom: 16 }}>
                    <Space>
                      <Button type="primary" onClick={fetchAllDevices} loading={transferLoading}>
                        加载设备
                      </Button>
                      <Button onClick={saveDeviceAssignment} disabled={transferLoading}>
                        保存分配
                      </Button>
                    </Space>
                  </div>
                  <Transfer
                    dataSource={allDevices.map(device => ({
                      key: device.id.toString(),
                      title: device.device_name,
                      description: `${device.device_no} | ${device.status === 1 ? '正常' : device.status === 0 ? '离线' : '故障'}`,
                    }))}
                    showSearch
                    targetKeys={targetKeys}
                    onChange={handleTransferChange}
                    filterOption={(inputValue, item) =>
                      item.title.indexOf(inputValue) !== -1 || item.description.indexOf(inputValue) !== -1
                    }
                    titles={['可用设备', '分组设备']}
                    render={item => `${item.title} (${item.description})`}
                    listStyle={{
                      width: 350,
                      height: 500,
                    }}
                    loading={transferLoading}
                  />
                </>
              ),
            },
          ]}
        />
      </Drawer>

      {/* 设备详情对话框 */}
      <Modal
        title="设备详情"
        visible={deviceDetailVisible}
        onCancel={() => setDeviceDetailVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDeviceDetailVisible(false)}>
            关闭
          </Button>,
        ]}
        width={600}
      >
        {currentDevice.id && (
          <Card bordered={false}>
            <div style={{ marginBottom: 16 }}>
              <Title level={4}>{currentDevice.device_name}</Title>
              <Tag color="blue">{currentDevice.device_no}</Tag>
            </div>
            
            <Paragraph>
              <Text strong>设备类型：</Text> {currentDevice.device_type}
            </Paragraph>
            
            <Paragraph>
              <Text strong>状态：</Text>
              <Badge
                status={
                  currentDevice.status === 1
                    ? 'success'
                    : currentDevice.status === 0
                    ? 'default'
                    : 'error'
                }
                text={
                  currentDevice.status === 1
                    ? '正常'
                    : currentDevice.status === 0
                    ? '离线'
                    : '故障'
                }
              />
            </Paragraph>
            
            <Paragraph>
              <Text strong>所属门店：</Text> {currentDevice.store_name || '未知'}
            </Paragraph>
            
            <Paragraph>
              <Text strong>所属场地：</Text> {currentDevice.venue_name || '未知'}
            </Paragraph>
            
            <Paragraph>
              <Text strong>IP地址：</Text> {currentDevice.ip_address || '未知'}
            </Paragraph>
            
            <Paragraph>
              <Text strong>最后在线时间：</Text>{' '}
              {currentDevice.last_online
                ? new Date(currentDevice.last_online * 1000).toLocaleString()
                : '未知'}
            </Paragraph>
            
            <Paragraph>
              <Text strong>描述：</Text> {currentDevice.description || '无'}
            </Paragraph>
          </Card>
        )}
      </Modal>
    </PageContainer>
  );
};

export default DeviceGroup;